package com.syh.app.basic.utils.net;

import android.net.ParseException;

import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
import com.syh.app.basic.base.BaseResponse;
import com.syh.app.basic.base.ErrorResponse;
import com.syh.app.basic.bean.LiveDataEvent;
import com.syh.app.basic.config.BasicConstants;
import com.syh.app.basic.config.ResponseCode;
import com.syh.app.basic.utils.ComUtil;
import com.syh.app.basic.utils.Loog;

import org.apache.http.conn.ConnectTimeoutException;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.NotSerializableException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.ConnectException;
import java.net.UnknownHostException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;
import retrofit2.HttpException;

import static com.syh.app.basic.config.ResponseCode.*;

/**
 * 创建者：SYH
 * 时间：2020/4/2 14:44
 * 编辑者：SYH、
 * 标签：
 * 补充说明：
 */
public abstract class ApiObserver<K> implements Observer<ResponseBody> {

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(ResponseBody responseBody) {
        try {
            String responseStr = responseBody.string();

            Gson gson = new Gson();

            try {
                ErrorResponse previewResponse = gson.fromJson(responseStr, ErrorResponse.class);
                if (previewResponse.getCode() == ResponseCode.ERROR_401||previewResponse.getCode()==ERROR_4000) {
                    EventBus.getDefault().post(new LiveDataEvent(BasicConstants.EVENT_LOGIN_STATUS));
                    return;
                } else if (previewResponse.getCode() == ERROR_411 || previewResponse.getCode() == ERROR_412) {
                    on411_412(previewResponse);
                    return;
                }
            } catch (Exception e) {
                onError(e);
            }

            K k = (K) gson.fromJson(responseStr, ComUtil.getClassT(ApiObserver.this, 0));

            if (k instanceof BaseResponse) {
                if (((BaseResponse) k).getCode() == ResponseCode.OK) {
                    onSuccess(k);
                } else {
                    onFailed(((BaseResponse) k).getCode(), ((BaseResponse) k).getMessage());
                }
            } else {
                onSuccess(k);
            }

        } catch (Exception e) {
            onError(e);
        }
    }

    @Override
    public void onError(Throwable e) {

//        Writer result = new StringWriter();
//        PrintWriter printWriter = new PrintWriter(result);
//        e.printStackTrace(printWriter);
//        printWriter.close();
//        Loog.d("ApiObserver" ,"result = "+ result.toString());

        int code = EXCEPTION_UNKNOW_ERROR;
        String message = null;
        if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof JsonSyntaxException
                || e instanceof JsonSerializer
                || e instanceof NotSerializableException
                || e instanceof ParseException) {
//            message = "解析错误";
        } else if (e instanceof ClassCastException) {
//            message = "类型转换错误";
        } else if (e instanceof ConnectException) {
            message = "连接失败";
            code = EXCEPTION_CONNECTION_ERROR;
        } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
//            message = "证书验证失败";
        } else if (e instanceof ConnectTimeoutException) {
            message = "连接超时";
            code = EXCEPTION_TIME_OUT_ERROR;
        } else if (e instanceof java.net.SocketTimeoutException) {
            message = "连接超时";
            code = EXCEPTION_TIME_OUT_ERROR;
        } else if (e instanceof UnknownHostException) {
//            message = "无法解析该域名";
        } else if (e instanceof NullPointerException) {
//            message = "NullPointerException";
        } else if (e instanceof HttpException) {
            message = "http异常" + e.getMessage();
        } else {
            message = "未知错误";
        }
        onFailed(code, message);
    }

    @Override
    public void onComplete() {

    }

    public abstract void onSuccess(K k);

    public abstract void onFailed(int code, String msg);

    public void on411_412(ErrorResponse errorResponse) {

    }
}
